<template>
	<view>
		<view class="border-bottom tn-mb-sm tn-pt-sm tn-pb-sm upload-container tn-flex">
			<view class="uplaod-item tn-flex items-center justify-center border-radius-10 bg-gray position-relative"
				v-if="props.images && props.images.length > 0" v-for="(item, index) in props.images" :key="index">
				<image mode="aspectFill" :src="item" @click="previewImage(index)">
				</image>
				<tn-badge value="icon-close" bg-color="tn-red" text-color="tn-white"
					@click="delImage(index)"></tn-badge>
			</view>
			<view class="uplaod-item tn-flex items-center justify-center border-radius-10 bg-gray"
				v-if="!props.images || props.images.length < props.max" @click="uploadImage">
				<tn-icon name="image" size="80rpx" color="#aaa" />
			</view>
		</view>
		<tn-modal ref="modalRef" />
	</view>
</template>

<script lang="ts" setup>
	import { ref } from 'vue';
	import type { TnModalInstance } from '@tuniao/tnui-vue3-uniapp';
	import { tip, uploadFile } from '@/util/util';

	const modalRef = ref<TnModalInstance>()
	const emit = defineEmits(['del', 'add'])
	interface Props {
		images : Array<string>,
		max : {
			require : false,
			default : 3,
			type : number
		}
	}

	const props = defineProps<Props>()

	const previewImage = (index : number) => {
		uni.previewImage({
			urls: props.images,
			current: index
		})
	}

	const delImage = (index : number) => {
		modalRef.value?.showModal({
			title: '操作提示',
			content: '确认删除该图片吗',
			showCancel: true,
			cancel: () => { },
			confirm: () => {
				emit('del', index)
			}
		})
	}

	const uploadImage = () => {
		uni.chooseImage({
			count: 1,
			sizeType: 'compressed',
			success: (res) => {
				if (res.tempFilePaths && res.tempFilePaths[0]) {
					let image = res.tempFilePaths[0]
					uploadFile(image).then((image : any) => {
						emit('add', image)
					}).catch(err => {
						tip({ title: err })
					})
				}
			}
		})
	}
</script>

<style lang="scss">
	.upload-container {
		.uplaod-item {
			width: 33%;
			height: 200rpx;
			margin-right: 15rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.uplaod-item:nth-child(3) {
			margin-right: 0;
		}
	}
</style>